package io.github.shenbinglife.springboot2.layui.admin.service.impl;

import io.github.shenbinglife.springboot2.layui.admin.dao.MenuDao;
import io.github.shenbinglife.springboot2.layui.admin.entity.Menu;
import io.github.shenbinglife.springboot2.layui.common.model.TreeNode;
import io.github.shenbinglife.springboot2.layui.common.service.impl.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * MenuService
 *
 * @author shenbing
 * @date 2021/4/12 22:33
 */
@Service
public class MenuService extends BaseService<Menu, MenuDao> {

    public List<TreeNode<Long>> getMenuTree(Long menuId, Boolean recursive) {
        List<Menu> menus = baseDao.findByParentIdOrderByOrdered(menuId);
        List<TreeNode<Long>> collect = menus.stream().map(i -> i.toTreeNode(menuId)).collect(Collectors.toList());
        if (recursive) {
            for (TreeNode<Long> treeNode : collect) {
                treeNode.setChildren(getMenuTree(treeNode.getId(), true));
            }
        }
        return collect;
    }

    public void deleteWithChildren(Long menuId) {
        List<Menu> menus = baseDao.findByParentIdOrderByOrdered(menuId);
        for (int i = 0; i < menus.size(); i++) {
            deleteWithChildren(menus.get(i).getId());
        }
        deleteById(menuId);
    }
}
